package com.sq.universe.base.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.sq.universe.base.entity.RespEntity;
import com.sq.universe.base.service.impl.BaseServiceImpl;
import com.sq.universe.base.dao.LogDao;
import com.sq.universe.base.entity.LogEntity;
import com.sq.universe.base.service.LogService;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.xpath.operations.Bool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author 孙乾 2020-09-07 21:25:01
*/
@Service
public class LogServiceImpl extends BaseServiceImpl<LogEntity, LogDao> implements LogService {

    @Autowired
    private LogDao logDao;


    /**
     * filterKeyWord 过滤关键字
     * @param data
     * @return
     */
    public RespEntity getLogs(JSONObject data){
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        String parentFiles = "";
        if(jarF.toString().contains("target")){
             parentFiles = jarF.getParentFile().getParentFile().getParentFile().toString() + File.separator + "logs" ;
        }else{
             parentFiles = jarF.getParentFile().toString() + File.separator + "logs" ;
        }

        List<Map<String,Object>> logList = new ArrayList<>();

        File dir = new File(parentFiles);
        for(File file : dir.listFiles()){
            Map<String,Object> map = new HashMap<>();
            map.put("key",file.getName());
            map.put("name",file.getName());
            map.put("fileName",file.getName());
            map.put("filePath",file.getAbsolutePath().replace(parentFiles,""));
            map.put("fileSize",file.length());
            if(StringUtils.isNotBlank(data.getStr("filterKey"))){
                this.filter(map, data, file);
                if((Boolean) map.get("concatKey")){
                    logList.add(map);
                }
            }else{
                logList.add(map);
            }
        }
        return RespEntity.success("查询成功",logList);
    }

    public void filter(Map fileInfo,JSONObject data,File file){
        Boolean concatKey = false;
        List<Integer> contentLines = new ArrayList();
        //java 8中这样写也可以
        try (BufferedReader br = Files.newBufferedReader(Paths.get(file.getAbsolutePath()))){
            String line;
            int i = 0;
            int allLines = 0;
            while ((line = br.readLine()) != null) {
                i++;
                allLines ++;
                if(StringUtils.isNotBlank(data.getStr("filterKey"))){
                    if(line.contains(data.getStr("filterKey"))){
                        contentLines.add(i);
                        concatKey = true;
                    }
                }
                System.out.println(line);
            }
            fileInfo.put("concatKey",concatKey);
            fileInfo.put("contentLines",contentLines);
            fileInfo.put("allLines",allLines);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getFile(String fileName){
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        String parentFiles = "";
        if(jarF.toString().contains("target")){
            parentFiles = jarF.getParentFile().getParentFile().getParentFile().toString() + File.separator + "logs" ;
        }else{
            parentFiles = jarF.getParentFile().toString() + File.separator + "logs" ;
        }
        parentFiles += File.separator + fileName ;
        return parentFiles;
    }

    @Override
    public RespEntity readByFilter(JSONObject filterCondition) {
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        String parentFiles = "";
        if(jarF.toString().contains("target")){
            parentFiles = jarF.getParentFile().getParentFile().getParentFile().toString() + File.separator + "logs" ;
        }else{
            parentFiles = jarF.getParentFile().toString() + File.separator + "logs" ;
        }
        File logFile = new File(parentFiles + File.separator + filterCondition.getStr("fileName"));
        return RespEntity.success(getFileByFilter(logFile,filterCondition));
    }

    @Override
    public RespEntity readBySimple(JSONObject filterCondition) {
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        String parentFiles = "";
        if(jarF.toString().contains("target")){
            parentFiles = jarF.getParentFile().getParentFile().getParentFile().toString() + File.separator + "logs" ;
        }else{
            parentFiles = jarF.getParentFile().toString() + File.separator + "logs" ;
        }
        File logFile = new File(parentFiles + File.separator + filterCondition.getStr("fileName"));
        return RespEntity.success(getFileBySimple(logFile,filterCondition));
    }

    @Override
    public RespEntity readAllLines(JSONObject filterCondition) {
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        String parentFiles = "";
        if(jarF.toString().contains("target")){
            parentFiles = jarF.getParentFile().getParentFile().getParentFile().toString() + File.separator + "logs" ;
        }else{
            parentFiles = jarF.getParentFile().toString() + File.separator + "logs" ;
        }
        File logFile = new File(parentFiles + File.separator + filterCondition.getStr("fileName"));
        int i = 0;
        try (BufferedReader br = Files.newBufferedReader(Paths.get(logFile.getAbsolutePath()))){
            String line;
            while ((line = br.readLine()) != null) {
                i++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespEntity.success(i);
    }

    @Override
    public RespEntity readByListen(JSONObject filterCondition) {
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        String parentFiles = "";
        if(jarF.toString().contains("target")){
            parentFiles = jarF.getParentFile().getParentFile().getParentFile().toString() + File.separator + "logs" ;
        }else{
            parentFiles = jarF.getParentFile().toString() + File.separator + "logs" ;
        }
        File logFile = new File(parentFiles + File.separator + filterCondition.getStr("fileName"));
        return RespEntity.success(getFileByListen(logFile,filterCondition));
    }

    public List<String > getFileByListen(File file,JSONObject filterCondition){
        Integer startRow = filterCondition.getInt("startRow");
        List<String > dataList= new ArrayList();
        try (BufferedReader br = Files.newBufferedReader(Paths.get(file.getAbsolutePath()))){
            String line;
            int i = 0;
            while ((line = br.readLine()) != null) {
                i++;
                if(startRow != null ){
                    if(i >= startRow){
                        dataList.add("<p>" + line + "</p>" );
                    }
                }
            }
            dataList.add(i + "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataList;
    }
    public List<String > getFileBySimple(File file,JSONObject filterCondition){
        //java 8中这样写也可以
        Integer startRow = filterCondition.getInt("startRow");
        Integer endRow = filterCondition.getInt("endRow");
        List<String > dataList= new ArrayList();
        try (BufferedReader br = Files.newBufferedReader(Paths.get(file.getAbsolutePath()))){
            String line;
            int i = 0;
            int allLines = 0;
            while ((line = br.readLine()) != null) {
                i++;
                if(startRow != null && endRow != null){
                    if(i >= startRow && i <= endRow){
                        dataList.add("<p>" + line + "</p>" );
                    }
                }else{
                    dataList.add("<p>" + line + "</p>" );
                }
            }
            dataList.add(i + "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataList;
    }

    public List<String > getFileByFilter(File file,JSONObject filterCondition){
        //java 8中这样写也可以
        List<String > dataList= new ArrayList();
        try (BufferedReader br = Files.newBufferedReader(Paths.get(file.getAbsolutePath()))){
            String line;
            int i = 0;
            int allLines = 0;
            while ((line = br.readLine()) != null) {
                i++;
                allLines ++;
                if(checkFilter(i,filterCondition,dataList)){
                    dataList.add("<p>" + line + "</p>" );
                }
                System.out.println();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataList;
    }

    public Boolean checkFilter(Integer line,JSONObject filterCondition,List<String > dataList){
        Integer currnetIndex = filterCondition.getInt("currnetIndex");
        Integer lineRange = filterCondition.getInt("lineRange");
        JSONArray rows = filterCondition.getJSONArray("contentLines");

        List<Integer> allowLines = new ArrayList<>();
        allowLines.add(rows.getInt(currnetIndex));
        if(filterCondition.get("showAll") != null && filterCondition.getBool("showAll")){
            allowLines.clear();
            for (int i = 0; i < rows.size(); i++) {
                allowLines.add( rows.getInt(i));
            }
        }
        for (int i = 0; i < allowLines.size(); i++) {
            Integer min = allowLines.get(i) - lineRange;
            Integer max = allowLines.get(i) + lineRange;
//            if(max.equals(line)){
//                dataList.add("<p><span style='color:#1890ff;font-weight: bold;font-size: 150%;'>----------------------------分割线----------------------------------------</span></p>");
//            }
            if(line < max && line > min ){
                return true;
            }
        }
        return false;
    }

}
